/*
 * IC Project - a prototype to test a hypothesis of collective intelligence
 * Copyright (C) 2012 Paolo Conte - paolo@concavi.net
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * This code is derived from the project ojoverse (2008, same author)
 * under the license GPL2. See <http://www.gnu.org/licenses/>.
 */

package org.ix.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Template {

    public static String parse(String sql, Map conditions) throws IllegalArgumentException {
        Pattern pattern = Pattern.compile("\\{([\\w\\.]+)\\}");
        Matcher matcher = pattern.matcher(sql);

        while (matcher.find()) {
            // System.out.println("Text " + matcher.group() + " found. Start at " + matcher.start() + ", end at " + matcher.end() + ".\n");
            String match = matcher.group(1);
            if (conditions.containsKey(match)) {
                sql = sql.replaceFirst("\\{" + match + "\\}", escape(conditions.get(match).toString()));
            }
        }

        return sql;
    }

    protected static String escape(String replacement) {
        return replacement.replace("\\", "\\\\").replace("$", "\\$");
    }

    public static void main(String[] args) {
        Template template = new Template();
        String sql = "SELECT DISTINCT DATA, COUNT(*) AS ROW_NUM"
                + "FROM TAB1 LEFT JOIN TAB2 ON F1 = F2 "
                + "WHERE NAME1 = {NAME1} AND NAME2 = {NAME2} "
                + "GROUP BY DATA "
                + "--{comment}";

        Map conditions = new HashMap();
        conditions.put("name1", "foo");
        conditions.put("name2", "212");
        conditions.put("comment", "a comment");

        String parsedSQL = template.parse(sql, conditions);

        System.out.println(parsedSQL + "\n");
    }
}
